package com.li.my_tiny_spring.beans.reader;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.io.IOUtils;

import com.li.my_tiny_spring.beans.definition.BeanDefinition;
import com.li.my_tiny_spring.exception.impl.MyIllegalStateException;
import com.li.my_tiny_spring.util.JsonUtil;
import com.li.my_tiny_spring.util.io.ResourceLoader;

public class JsonBeanDefinitionReader extends AbstractBeanDefinitionReader{

	public JsonBeanDefinitionReader(ResourceLoader resourceLoader) {
		super(resourceLoader);
	}

	@Override
	protected Map<String, BeanDefinition> doLoadBeanDefinitions(InputStream inputStream) {
		try {
			String inputStr = IOUtils.toString(inputStream, "UTF-8");
			List<BeanDefinition> list = JsonUtil.toList(inputStr, BeanDefinition.class);
			if(CollectionUtils.isEmpty(list)) {
				return new HashMap<>();
			}
			Map<String,BeanDefinition> result = new HashMap<>();
			for (BeanDefinition beanDefinition : list) {
				result.put(beanDefinition.getBeanName(), beanDefinition);
			}
			return result;
		} catch (IOException e) {
			throw new MyIllegalStateException(e);
		}
	}


		
	

}
